//
//  LJM_SONG_ViewController.m
//  wind
//
//  Created by 李金明 on 16/1/18.
//  Copyright © 2016年 李金明. All rights reserved.
//

#import "LJM_SONG_ViewController.h"
#import "LJM_SONG_Sub_ViewController.h"
#import "LJM_SONG_Main_CollectionViewCell.h"
#import "LJM_SONG_Main_Model.h"
#import "LJM_SONG_Root_Sub_ViewController.h"
//歌单网址
#define SONGONURL @"http://search.dongting.com/songlist/search?q=tag:"
#define SONGDOWNURL @"&page=1&size=10&app=ttpod&v=v8.1.3.2015112716&user_id=0&mid=iPhone4S&f=f320&s=s310&imsi=&hid=&splus=7.0.4&active=1&net=2&openudid=1389d9dc18cb741587d90a5aead8646421f95dc0&idfa=C9BC818C-A0F5-4F04-8F8D-841910E08DF7&utdid=VmGiKEXHDQ0DAIL2FOnFFzxV&alf=201200&bundle_id=com.ttpod.music&latitude=&longtitude="

//collectionfowl的坐标
#define COLLECTIONFOWLEDGE 5//边界
#define COLLECTWIDTH 20
#define COLLECTHEADHEIGHT 20//区头的高度
#define HEADHEIGHT 50//头视图的高度
#define HEADALLBUTTONHEIGHT 30//全部按钮高度
#define HEADALLBUTTONWIDTH 80//全部按钮的宽度
@interface LJM_SONG_ViewController () <UICollectionViewDelegate, UICollectionViewDataSource, Song_Sub_BackDelegate, song_Sub_ChangeView, SubBackNavigationDelegate>
//LJM_SONG_Root_Sub_ViewController的返回协议
- (void)SubBackNavigationDelegate;
//Song_Sub_VC协议的方法改变界面
- (void)backSongChangeViewStr:(NSString *)str;
//Song_Sub_VC协议的方法返回
- (void)backSongDelegate;
@property (nonatomic, retain) UIButton *bactButton;
@property (nonatomic, retain) UIView *barview;
@property (nonatomic, retain) UICollectionView *collectionV;
@property (nonatomic, retain) UIView *headView;
@property (nonatomic, retain) UIButton *headAllButton;
@property (nonatomic, retain) UIButton *headHotButton;
@property (nonatomic, retain) UIButton *headNewButton;
@property (nonatomic, copy) NSString *hotOrNewStr;
@end

@implementation LJM_SONG_ViewController
- (void)dealloc
{
    self.backDelegate = nil;
    [_hotOrNewStr release];
    [_headAllButton release];
    [_headHotButton release];
    [_headNewButton release];
    [_headView release];
    [_dataArr release];
    [_collectionV release];
    [_bactButton release];
    [_barview release];
    [super dealloc];
}
- (void)setDataArr:(NSMutableArray *)dataArr
{
    if (_dataArr != dataArr) {
        [_dataArr release];
        _dataArr = [dataArr retain];
        
    }
    [self.collectionV reloadData];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
//自定义navigationBar
    [self navigationBarView];
//添加一个上视图
    [self addHeardView];
//添加collectionView
    [self addCollectionView];
    self.hotOrNewStr = @"hot";
}
- (void)addHeardView
{
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, HEADHEIGHT)];
    self.headView.backgroundColor = [UIColor whiteColor];
    self.headView.userInteractionEnabled = YES;
    [self.view addSubview:self.headView];
    [_headView release];
    self.headAllButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.headAllButton setTitle:@"全部  >" forState:UIControlStateNormal];
    [self.headAllButton addTarget:self action:@selector(headButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.headAllButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    self.headAllButton.titleLabel.font = [UIFont systemFontOfSize:16];
    //增加边框
    [self.headAllButton.layer setMasksToBounds:YES];
    [self.headAllButton.layer setBorderWidth:1.0];


    self.headAllButton.backgroundColor = [UIColor whiteColor];
    [self.headView addSubview:self.headAllButton];
    
[self.headAllButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.headView.mas_left).offset(10);
    make.centerY.equalTo(self.headView.mas_centerY);
    make.height.mas_equalTo(@HEADALLBUTTONHEIGHT);
    make.width.mas_equalTo(@HEADALLBUTTONWIDTH);
    
}];
    
    self.headNewButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.headNewButton addTarget:self action:@selector(headButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.headNewButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.headNewButton setTitle:@"最新" forState:UIControlStateNormal];
    [self.headNewButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.headNewButton setTitleColor:[UIColor colorWithRed:69 / 255.0 green:175 / 255.0 blue:248 / 255.0 alpha:1.0] forState:UIControlStateSelected];
    [self.headView addSubview:self.headNewButton];
    [self.headNewButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.headView).offset(- 10);
        make.centerY.equalTo(self.headView);
        make.width.mas_equalTo(@60);
        make.height.mas_equalTo(@30);
    }];
    
    
    self.headHotButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.headHotButton addTarget:self action:@selector(headButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        self.headHotButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.headHotButton setTitle:@"最热" forState:UIControlStateNormal];
    [self.headHotButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
     [self.headHotButton setTitleColor:[UIColor colorWithRed:69 / 255.0 green:175 / 255.0 blue:248 / 255.0 alpha:1.0] forState:UIControlStateSelected];
    self.headHotButton.selected = YES;
    
    [self.headView addSubview:self.headHotButton];
   
    [self.headHotButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.headNewButton.mas_left).offset(10);
        make.centerY.equalTo(self.headView);
        make.width.mas_equalTo(@60);
        make.height.mas_equalTo(@30);
    }];
    
    

    
    
    
}
#pragma head上按钮的动作
- (void)headButtonAction:(UIButton *)sender
{
   

    if (sender == self.headAllButton) {

        LJM_SONG_Sub_ViewController *subVC = [[LJM_SONG_Sub_ViewController alloc] init];
        subVC.backDelegate = self;
        subVC.backChangeDelegate = self;
        [self.navigationController pushViewController:subVC animated:YES];
        [self.barview removeFromSuperview];
        subVC.navigationItem.hidesBackButton = YES;
        
        
    }
    if (sender == self.headHotButton) {
self.hotOrNewStr = @"hot";
        self.headHotButton.selected = YES;
        self.headNewButton.selected = NO;
        [self getHotData];
    }
    if (sender == self.headNewButton) {
self.hotOrNewStr = @"new";
        self.headHotButton.selected = NO;
        self.headNewButton.selected = YES;
        //获取new的数据
        [self getNewData];
    }

}
#pragma 获取hot的数据
- (void)getHotData
{
    NSString *titleStr = [NSString stringWithFormat:@"%@  >", @"最热"];
    [self.headAllButton setTitle:titleStr forState:UIControlStateNormal];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@", SONGONURL, @"最热", SONGDOWNURL];
    NSMutableArray *dataArr = [NSMutableArray array];
    [LJMNetworkTool getNetWithURL:urlStr body:nil headFile:nil responseStyle:LJMResponseJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        if (responseObject) {
            
            for (NSMutableDictionary *tempDic in [responseObject objectForKey:@"data"]) {
                
                LJM_SONG_Main_Model *model = [[LJM_SONG_Main_Model alloc] init];
                [model initWithDic:tempDic];
                [dataArr addObject:model];
                [model release];
                
            }
            [self.dataArr removeAllObjects];
            self.dataArr = dataArr;
#pragma 缓存数据到本地
            NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[urlStr hash]];
            // 存储的沙盒路径
            NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            // 归档
            [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
            
        }
        [self.collectionV reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[urlStr hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 反归档
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
        
        if (result) {
            
            for (NSMutableDictionary *tempDic in [result objectForKey:@"data"]) {
                
                LJM_SONG_Main_Model *model = [[LJM_SONG_Main_Model alloc] init];
                [model initWithDic:tempDic];
                [dataArr addObject:model];
                [model release];
                
            }
            [self.dataArr removeAllObjects];
            self.dataArr = dataArr;
        }
        [self.collectionV reloadData];
        
    }];

}
#pragma 获取new的数据
- (void)getNewData
{
    NSString *titleStr = [NSString stringWithFormat:@"%@  >", @"最新"];
    [self.headAllButton setTitle:titleStr forState:UIControlStateNormal];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@", SONGONURL, @"最新", SONGDOWNURL];
    NSMutableArray *dataArr = [NSMutableArray array];
    [LJMNetworkTool getNetWithURL:urlStr body:nil headFile:nil responseStyle:LJMResponseJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        if (responseObject) {

        for (NSMutableDictionary *tempDic in [responseObject objectForKey:@"data"]) {
            
            LJM_SONG_Main_Model *model = [[LJM_SONG_Main_Model alloc] init];
            [model initWithDic:tempDic];
            [dataArr addObject:model];
            [model release];
            
        }
            [self.dataArr removeAllObjects];
            self.dataArr = dataArr;
#pragma 缓存数据到本地
            NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[urlStr hash]];
            // 存储的沙盒路径
            NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            // 归档
            [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
            
}
        [self.collectionV reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[urlStr hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 反归档
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
        
        if (result) {
            
            for (NSMutableDictionary *tempDic in [result objectForKey:@"data"]) {
                
                LJM_SONG_Main_Model *model = [[LJM_SONG_Main_Model alloc] init];
                [model initWithDic:tempDic];
                [dataArr addObject:model];
                [model release];
                
            }
            [self.dataArr removeAllObjects];
            self.dataArr = dataArr;
        }
        [self.collectionV reloadData];
        
    }];

}
#pragma 添加collectionView
- (void)addCollectionView
{
    UICollectionViewFlowLayout *flowLy = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    flowLy.sectionInset = UIEdgeInsetsMake(COLLECTIONFOWLEDGE + COLLECTIONFOWLEDGE, COLLECTIONFOWLEDGE, COLLECTIONFOWLEDGE, COLLECTIONFOWLEDGE);
    flowLy.itemSize = CGSizeMake((self.view.frame.size.width - COLLECTWIDTH) / 2, (self.view.frame.size.width - COLLECTWIDTH) / 3 + COLLECTWIDTH);
    flowLy.minimumLineSpacing = COLLECTIONFOWLEDGE;
    flowLy.minimumInteritemSpacing = COLLECTIONFOWLEDGE;
    self.collectionV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HEADHEIGHT, self.view.frame.size.width, self.view.frame.size.height - 200) collectionViewLayout:flowLy];
    self.collectionV.delegate = self;
    self.collectionV.dataSource = self;
    self.collectionV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionV];
    [_collectionV release];
    
    [self.collectionV registerClass:[LJM_SONG_Main_CollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
}
#pragma collectionView的协议方法
#pragma 个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArr.count;
}
#pragma cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LJM_SONG_Main_CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    LJM_SONG_Main_Model *model = [self.dataArr objectAtIndex:indexPath.row];
    
    [cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.pic_url] placeholderImage:[UIImage imageNamed:@"zhanwei"]];
    cell.titleLab.text = model.title;
    
    return cell;
}
#pragma 点击
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    LJM_SONG_Root_Sub_ViewController *subVC = [[LJM_SONG_Root_Sub_ViewController alloc] init];
    subVC.backDelegate = self;
     LJM_SONG_Main_Model *model = [self.dataArr objectAtIndex:indexPath.row];
    subVC.type = @"SONG";
    subVC.imageUrl = model.pic_url;
    subVC._id = model._id;
    [self.navigationController pushViewController:subVC animated:YES];
    [subVC release];
    [self.barview removeFromSuperview];
    subVC.navigationItem.hidesBackButton = YES;

}
#pragma 自定义navigationBar
- (void)navigationBarView
{
    
    self.barview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, NAVIGATIONBARHEIGHT)];
    self.barview.userInteractionEnabled = YES;
    self.barview.backgroundColor = [UIColor colorWithRed:69 / 255.0 green:175 / 255.0 blue:248 / 255.0 alpha:1.0];
    [self.navigationController.navigationBar addSubview:self.barview];
    [_barview release];
    self.bactButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.bactButton setTitle:@"返回" forState:UIControlStateNormal];
    [self.bactButton addTarget:self action:@selector(backButton) forControlEvents:UIControlEventTouchUpInside];
    [self.bactButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.barview addSubview:self.bactButton];
    [self.bactButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.barview.mas_left).offset(10);
        make.width.mas_equalTo(@50);
        make.bottom.equalTo(self.barview.mas_bottom).offset(-5);
        make.height.mas_equalTo(@30);
    }];
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.text = @"歌单";
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.font = [UIFont boldSystemFontOfSize:20];
    titleLab.textColor = [UIColor whiteColor];
    [self.barview addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.barview.mas_centerX);
        make.width.mas_equalTo(@50);
        make.centerY.equalTo(self.bactButton.mas_centerY);
        make.height.mas_equalTo(@30);
    }];
    
}
#pragma 返回的动作
- (void)backButton
{
    [self.navigationController popViewControllerAnimated:YES];
    [self.barview removeFromSuperview];
    [self.backDelegate backSONGAction];
}
#pragma song_sub_VC协议的方法
- (void)backSongDelegate
{
[self navigationBarView];
}
#pragma Song_Sub_VC协议的方法改变界面
- (void)backSongChangeViewStr:(NSString *)str
{
    [self getDataStr:str];
}
#pragma 获取数据
- (void)getDataStr:(NSString *)str
{
    NSString *titleStr = [NSString stringWithFormat:@"%@  >", str];
    [self.headAllButton setTitle:titleStr forState:UIControlStateNormal];
    
    if ([self.hotOrNewStr isEqualToString:@"hot"]) {
        NSString *urlStr = [NSString stringWithFormat:@"%@%@|%@%@", SONGONURL, @"最热", str, SONGDOWNURL];
        NSMutableArray *dataArr = [NSMutableArray array];
        [LJMNetworkTool getNetWithURL:urlStr body:nil headFile:nil responseStyle:LJMResponseJSON success:^(NSURLSessionDataTask *task, id responseObject) {
            if (responseObject) {
                
                for (NSMutableDictionary *tempDic in [responseObject objectForKey:@"data"]) {
                    
                    LJM_SONG_Main_Model *model = [[LJM_SONG_Main_Model alloc] init];
                    [model initWithDic:tempDic];
                    [dataArr addObject:model];
                    [model release];
                    
                }
                [self.dataArr removeAllObjects];
                self.dataArr = dataArr;
#pragma 缓存数据到本地
                NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[urlStr hash]];
                // 存储的沙盒路径
                NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                // 归档
                [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
                
            }
            [self.collectionV reloadData];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
            // 缓存的文件夹
            NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[urlStr hash]];
            NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            // 反归档
            id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
            
            if (result) {
                
                for (NSMutableDictionary *tempDic in [result objectForKey:@"data"]) {
                    
                    LJM_SONG_Main_Model *model = [[LJM_SONG_Main_Model alloc] init];
                    [model initWithDic:tempDic];
                    [dataArr addObject:model];
                    [model release];
                    
                }
                [self.dataArr removeAllObjects];
                self.dataArr = dataArr;
            }
            [self.collectionV reloadData];
            
        }];

    } else {
        NSString *urlStr = [NSString stringWithFormat:@"%@%@|%@%@", SONGONURL, @"最新", str, SONGDOWNURL];
        NSMutableArray *dataArr = [NSMutableArray array];
        [LJMNetworkTool getNetWithURL:urlStr body:nil headFile:nil responseStyle:LJMResponseJSON success:^(NSURLSessionDataTask *task, id responseObject) {
            if (responseObject) {
                
                for (NSMutableDictionary *tempDic in [responseObject objectForKey:@"data"]) {
                    
                    LJM_SONG_Main_Model *model = [[LJM_SONG_Main_Model alloc] init];
                    [model initWithDic:tempDic];
                    [dataArr addObject:model];
                    [model release];
                    
                }
                [self.dataArr removeAllObjects];
                self.dataArr = dataArr;
#pragma 缓存数据到本地
                NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[urlStr hash]];
                // 存储的沙盒路径
                NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                // 归档
                [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
                
            }
            [self.collectionV reloadData];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
            // 缓存的文件夹
            NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[urlStr hash]];
            NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            // 反归档
            id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
            
            if (result) {
                
                for (NSMutableDictionary *tempDic in [result objectForKey:@"data"]) {
                    
                    LJM_SONG_Main_Model *model = [[LJM_SONG_Main_Model alloc] init];
                    [model initWithDic:tempDic];
                    [dataArr addObject:model];
                    [model release];
                    
                }
                [self.dataArr removeAllObjects];
                self.dataArr = dataArr;
            }
            [self.collectionV reloadData];
            
        }];
    }
}
#pragma LJM_SONG_Root_Sub_ViewController的返回协议
- (void)SubBackNavigationDelegate
{
    [self navigationBarView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
